package com.sgb.kjwl.view.ui.activity.self;

import android.annotation.SuppressLint;
import android.content.Intent;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.lifecycle.ViewModelProvider;

import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityAddCarBinding;
import com.sgb.kjwl.model.entity.AllFunction;
import com.sgb.kjwl.model.entity.self.CarInfoEntity;
import com.sgb.kjwl.model.entity.self.CarriageSelectEntity;
import com.sgb.kjwl.model.entity.self.EnergyTypeEntity;
import com.sgb.kjwl.model.entity.transport.GoodsInfoTypeEntity3;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.utils.ImageUtil;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.PickerHelper;
import com.sgb.kjwl.utils.RangeFocusChangeListener;
import com.sgb.kjwl.utils.VehicleConstant;
import com.sgb.kjwl.view.constant.RequestCode;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.LogisticsEvent;
import com.sgb.kjwl.view.ui.adapter.transport.CarFuncationPopWindow;
import com.sgb.kjwl.view.widget.ChoosePictureDialog;
import com.swgk.core.util.ArrayUtil;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.self.AddCarInfoModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MLog;
import com.swgk.core.util.MToast;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 完善车辆信息
 */
public class AddCarInfoActivity extends AppActivity {
   // @Inject
    AddCarInfoModel viewModel;
    ActivityAddCarBinding binding;
    private List<GoodsInfoTypeEntity3> carsTypeData;
    List<GoodsInfoTypeEntity3> carsLengthData;
    // 一级联动数据
    public static List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    public static List<List<AddressEntity<List<AddressEntity>>>> opt2 = new ArrayList<>();
    // 三级联动数据
    public static List<List<List<AddressEntity>>> opt3 = new ArrayList<>();
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private int carModelPosition;
    private int carLengthPosition;
    private int carColorPostition;
    private int carEnergyTypePostiton;
    public int DRIVING_LICENS = 1;  //行驶照
    public int DRIVING_LICENS_ATTACHED = 2;//附页
    public int TRANSPORT_PIC = 3;//道路运输证

    private int type;
    String driverPic, driverPic2;
    int carId;
    long carNo;
    private int intentioncityPosition1;
    private int intentioncityPosition2;

    List<CarriageSelectEntity> carColorInfo = new ArrayList<>();
    private ChoosePictureDialog mChoosePictureDialog;
    private File vehicleLicenseFile;
    private File vehicleLicenseFile2;
    private File vehicleLicenseFile3;
    private OptionsPickerView<GoodsInfoTypeEntity3> carModePop;
    private OptionsPickerView<GoodsInfoTypeEntity3> carLengthPop;
    private List<AllFunction> mlist;
    CarFuncationPopWindow funcationPopWindow;
    StringBuilder sb, no;

    List<File> files = new ArrayList<>();
    private CarInfoEntity myCarInfo;
    private long acquireTime;
    private long insuranceTime;
    private long annualInspectionTime;
    private long upMaintainTime;
    private int uploadImgType;
    private List<EnergyTypeEntity> entityList = new ArrayList<>();
    private OptionsPickerView mEnergyPicker;

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(this, R.layout.activity_add_car);
        viewModel = new ViewModelProvider(this).get(AddCarInfoModel.class);
        binding.setOnClick(this);
        binding.include.ivBack.setOnClickListener(this);
        binding.tvLocation.setOnClickListener(this);
        binding.tvPosition.setOnClickListener(this);
        binding.llCarLengh.setOnClickListener(this);
        binding.llCarModel.setOnClickListener(this);
        binding.llCarColor.setOnClickListener(this);
        binding.llCarUpperDoorAddress.setOnClickListener(this);
        binding.llCarInsuranceTime.setOnClickListener(this);
        binding.llCarAnnualInspectionTime.setOnClickListener(this);
        binding.llCarMaintenanceTime.setOnClickListener(this);
        binding.carCurrentGo.setOnClickListener(this);
        binding.llVehicleEnergyType.setOnClickListener(this);
        binding.edtHeight.setOnFocusChangeListener(new RangeFocusChangeListener(0.01, 999.99));
        funcationPopWindow = new CarFuncationPopWindow(this);
        funcationPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                List<AllFunction> entity = (List<AllFunction>) key1;
                setMlist(entity);
            }
        });
        CarriageSelectEntity entity1 = new CarriageSelectEntity();
        entity1.setName("黄");
        entity1.setNo("2");
        CarriageSelectEntity entity2 = new CarriageSelectEntity();
        entity2.setName("蓝");
        entity2.setNo("1");
        CarriageSelectEntity entity3 = new CarriageSelectEntity();
        entity3.setName("绿");
        entity3.setNo("9");
        carColorInfo.add(entity1);
        carColorInfo.add(entity2);
        carColorInfo.add(entity3);
        binding.include.titleView.setText("车辆信息");
        binding.nextView.setOnClickListener(this);
        carId = getIntent().getIntExtra("carId", 0);
        carNo = getIntent().getLongExtra("carNo", 0);
        if (carNo != 0) {
            try {
                viewModel.carInfoEntity.get().setId(carId);
            }catch (Exception e){

            }
            myCarInfo = (CarInfoEntity) getIntent().getSerializableExtra("carInfo");
            if (myCarInfo != null) {
                setCarInfo(myCarInfo);
            } else {
                viewModel.getCarDetail(this,carNo);

            }
        }

    }

    public void setCarInfo(CarInfoEntity carInfo) {
        carId = carInfo.getId();
        RequestOptions options = new RequestOptions().placeholder(R.drawable.car_info_bg_img).error(R.drawable.car_info_bg_img).apply(new RequestOptions().centerCrop());
        myCarInfo = carInfo;
        viewModel.carInfoEntity.set(carInfo);
        if (!TextUtils.isEmpty(carInfo.getCarLenName())) {
            String[] len = viewModel.carInfoEntity.get().getCarLenName().split("米");
            double carLen = Double.valueOf(len[0]);
            viewModel.carInfoEntity.get().setCarLen(carLen);
        }
        if (!TextUtils.isEmpty(myCarInfo.getMainCertificate())) {
            binding.imgDel1.setVisibility(View.VISIBLE);
            Glide.with(getActivity()).load(myCarInfo.getMainCertificate()).apply(options).into(binding.ivCertificates);
        }
        if (!TextUtils.isEmpty(myCarInfo.getViceCertificate())) {
            binding.imgDel2.setVisibility(View.VISIBLE);
            Glide.with(getActivity()).load(myCarInfo.getViceCertificate()).apply(options).into(binding.ivCertificatesCarphoto);
        }
        if (!TextUtils.isEmpty(myCarInfo.getTransportCertificateMain())) {
            binding.imgDel3.setVisibility(View.VISIBLE);
            Glide.with(getActivity()).load(myCarInfo.getTransportCertificateMain()).apply(options).into(binding.ivTransportCertificates);
        }
        if (!TextUtils.isEmpty(myCarInfo.getTransportCertificateNum())) {
            binding.tvTransportNo.setText(myCarInfo.getTransportCertificateNum());
        }
        if (myCarInfo.getLatitude() != 0 && myCarInfo.getLongitude() != 0
                && !TextUtils.isEmpty(myCarInfo.getProvinceNo())) {
            if((myCarInfo.getDetailAddress().contains("省")||myCarInfo.getDetailAddress().contains("市"))){
                binding.tvLocation.setText(myCarInfo.getDetailAddress());
            }else {
                binding.tvLocation.setText(String.format("%s%s%s%s",
                        myCarInfo.getProvinceName(),
                        myCarInfo.getCityName(),
                        myCarInfo.getDistrictName(),
                        myCarInfo.getDetailAddress()));
            }
            binding.etCargoOrdersAddress.setVisibility(View.GONE);
            binding.etCargoOrdersAddress.setText(myCarInfo.getDetailAddress());
        }
        binding.tvCarLengh.setText(myCarInfo.getCarLenName());
        binding.tvCarModel.setText(myCarInfo.getCarTypeName());
        if (!TextUtils.isEmpty(myCarInfo.getWeight())) {
            binding.tvCarWeight.setText(NumberUtil.trim0(myCarInfo.getWeight()) + "");
        }
        binding.llCarLengh.setVisibility(View.VISIBLE);
        binding.vLine.setVisibility(View.VISIBLE);
        if (!TextUtils.isEmpty(myCarInfo.getDetailAddress())) {
            binding.etCargoOrdersAddress.setText(myCarInfo.getDetailAddress());
            binding.etCargoOrdersAddress.setVisibility(View.GONE);
        }
        for (CarriageSelectEntity entity : carColorInfo) {
            if (entity.getNo().equals(myCarInfo.getLicensePlateColor())) {
                binding.tvCarColor.setText(entity.getName());
                break;
            }

        }
        if (myCarInfo.getAcquireTime() != 0) {
            binding.tvTime.setText(DateUtils.timestampToDate(myCarInfo.getAcquireTime()));
        }
        binding.tvIsunload.setText(VehicleConstant.getIsDumpStr(myCarInfo.getIsDump()));
        if (!TextUtils.isEmpty(myCarInfo.getFunctionNos())) {
            binding.carFunction.setText(myCarInfo.getFunctionNos());
        }

        if (!TextUtils.isEmpty(myCarInfo.getHeightHurdle())) {
            binding.edtHeight.setText(NumberUtil.trim0(myCarInfo.getHeightHurdle()));
        }
        if (!TextUtils.isEmpty(myCarInfo.getCarProvinceName())&&!TextUtils.isEmpty(myCarInfo.getCarCityName())&&!TextUtils.isEmpty(myCarInfo.getCarDistrictName())){
            binding.carUpperDoorAddress.setText(myCarInfo.getCarProvinceName()+""+myCarInfo.getCarCityName()+""+myCarInfo.getCarDistrictName());
        }
        if (myCarInfo.getInsuranceTime()!=null){
            binding.carInsuranceTime.setText(DateUtils.timestampToDate(myCarInfo.getInsuranceTime()));
        }
        if (myCarInfo.getAnnualInspectionTime()!=null){
            binding.carAnnualInspectionTime.setText(DateUtils.timestampToDate(myCarInfo.getAnnualInspectionTime()));
        }
        if (myCarInfo.getUpMaintainTime()!=null){
            binding.carMaintenanceTime.setText(DateUtils.timestampToDate(myCarInfo.getUpMaintainTime()));
        }
        if (myCarInfo.getCarYears()!=null){
            if (myCarInfo.getCarYears()==0){
                binding.carVehicleLife.setText("");
            }else {
                binding.carVehicleLife.setText(myCarInfo.getCarYears().toString());
            }
        }else {
            binding.carVehicleLife.setText("");
        }
        if (!TextUtils.isEmpty(myCarInfo.getIntentionProvinceName())&&!TextUtils.isEmpty(myCarInfo.getIntentionCityName())){
            binding.carCurrentGo.setText(myCarInfo.getIntentionProvinceName()+myCarInfo.getIntentionCityName());
        }
        if (!TextUtils.isEmpty(myCarInfo.getImageVehicleEnergyType())){
            binding.vehicleEnergyType.setText(myCarInfo.getImageVehicleEnergyType());
            viewModel.carInfoEntity.get().setImageSourceCode(myCarInfo.getImageSourceCode());
        }
        if (!TextUtils.isEmpty(myCarInfo.getImageIssuingAuthority())){
            binding.issuingAuthority.setText(myCarInfo.getImageIssuingAuthority());
        }
        viewModel.getCarsLength(myCarInfo.getCarTypeNo());
        viewModel.getCarFuncation();
        viewModel.getAddressModel(this);
        viewModel.getCarEnergy();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }


    @Override
    protected void init() {
        viewModel.uploadImgType.observe(this,type->{
            uploadImgType = type;
        });
        viewModel.uploadImg.observe(this,uploadlist->{
            uploadImgSuccess(uploadlist,uploadImgType);
        });
        viewModel.CarsTypeData.observe(this,CarsTypeData->{
            getCarsTypeData(CarsTypeData);
        });

        viewModel.CarsLengthData.observe(this,CarsLengthData->{
            getCarsLengthData(CarsLengthData);
        });
        viewModel.AddressData.observe(this,AddressData->{
            initAddressData(AddressData);
        });
        viewModel.CarInfo.observe(this,CarInfo->{
            setCarInfo(CarInfo);
        });
        viewModel.MyCarList.observe(this,MyCarList->{
            setMyCarList(MyCarList);
        });
        viewModel.SubMit.observe(this,submit->{
            finish();
        });
        viewModel.energyTypeList.observe(this,energyTypeEntities -> {
            showCarEnergyPop(energyTypeEntities);
        });
    }

    @Override
    public void onClick(View v) {
        closeKeybord();
        switch (v.getId()) {
            case R.id.iv_back:
                finish();
                break;
            case R.id.tv_location:
            case R.id.tv_position:
                AMapDialog.launch(this,myCarInfo.getLatitude(),myCarInfo.getLongitude());
                break;
            case R.id.ll_car_lengh:
                String carModel = binding.tvCarModel.getText().toString();
                if (TextUtils.isEmpty(carModel)) {
                    MToast.showToast(this, "请先选择车型");
                    return;
                }
                if (carsLengthData != null && carsLengthData.size() > 0) {
                    showCarLengthPop();
                } else {
                    MToast.showToast(this, "该车型下暂无关联车长 请更换其它车型");
                }
                break;
            case R.id.ll_car_model:
                if (carsTypeData != null) {
                    showCarModelPop();
                } else {
                    viewModel.getCarsType();
                }
                break;
            case R.id.iv_certificates:
                showPictureDailog(R.drawable.img_cy_mian, DRIVING_LICENS);
                //  getCerImage(DRIVING_LICENS);


                break;
            case R.id.iv_certificates_carphoto:
                showPictureDailog(R.drawable.img_cy_second_page, DRIVING_LICENS_ATTACHED);
                // getCerImage(DRIVING_LICENS_ATTACHED);

                break;
            case R.id.iv_transport_certificates:
                showPictureDailog(R.drawable.img_sl_dluzy, TRANSPORT_PIC);
                break;


            case R.id.next_view:
                //   String carNumber = binding.tvCarNum.getText().toString();
                String location = binding.tvLocation.getText().toString();
                String len = binding.tvCarLengh.getText().toString();
                String model = binding.tvCarModel.getText().toString();
                String weight = binding.tvCarWeight.getText().toString();
                String carColor = binding.tvCarColor.getText().toString();
                String transportNo = binding.tvTransportNo.getText().toString();


                if (TextUtils.isEmpty(model)) {
                    MToast.showToast(this, "请选择车型");
                    return;
                }
                if (TextUtils.isEmpty(len)) {
                    MToast.showToast(this, "请选择车长");
                    return;
                }
                if (TextUtils.isEmpty(weight)) {
                    MToast.showToast(this, "请输入载重");
                    return;
                } else if (Double.valueOf(weight) > 999.99) {
                    MToast.showToast(this, "额定载重不能大于999.99");
                    return;
                }

                if (TextUtils.isEmpty(carColor)) {
                    MToast.showToast(this, "请选择车牌颜色");
                    return;
                }
                if (TextUtils.isEmpty(location)) {
                    MToast.showToast(this, "请选择地址");
                    return;
                }
                if (!TextUtils.isEmpty(transportNo)) {
                    if (transportNo.length() < 12) {
                        MToast.showToast(getActivity(), "请输入道路运输证12位编号");
                        return;
                    }
                }
                if (!TextUtils.isEmpty(binding.edtHeight.getText().toString()) && NumberUtil.convertToFloat(binding.edtHeight.getText().toString()) > 999.99) {
                    binding.edtHeight.setText("999.99");
                }

                if (!TextUtils.isEmpty(binding.edtHeight.getText().toString()) && NumberUtil.convertToFloat(binding.edtHeight.getText().toString()) < 0.01) {
                    binding.edtHeight.setText("0.01");
                }
                if (TextUtils.isEmpty(binding.carFunction.getText())) {
                    viewModel.carInfoEntity.get().setFunctionNo("");
                } else {
                    viewModel.carInfoEntity.get().setFunctionNo(no.substring(0, no.length() - 1));
                }
                viewModel.carInfoEntity.get().setImageIssuingAuthority(binding.issuingAuthority.getText().toString());
                if (!TextUtils.isEmpty(binding.carVehicleLife.getText())){
                    int put = Integer.parseInt(binding.carVehicleLife.getText().toString());
                    if (put<1){
                        MToast.showToast(getActivity(), "车辆年限不能小于极小值");
                        return;
                    }
                    if (put>50){
                        MToast.showToast(getActivity(), "车辆年限不能大于极大值");
                        return;
                    }
                }
                viewModel.carInfoEntity.get().setTelphone(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.LOGIN_PHONE, ""));
                viewModel.carInfoEntity.get().setWeight(NumberUtil.trim0(weight));
                viewModel.carInfoEntity.get().setDetailAddress(location);
                viewModel.carInfoEntity.get().setTransportCertificateNum(transportNo);
                viewModel.carInfoEntity.get().setCarYears(TextUtils.isEmpty(binding.carVehicleLife.getText().toString())?null:NumberUtil.convertToInt(binding.carVehicleLife.getText().toString()));
                if (!TextUtils.isEmpty(binding.edtHeight.getText().toString())) {
                    viewModel.carInfoEntity.get().setHeightHurdle(binding.edtHeight.getText().toString());
                }
                viewModel.authCar(this);
                break;
            case R.id.ll_car_color:
                showCarColorPop();
                break;
            case R.id.car_function:
                if (mlist == null) {
                    return;
                }
                funcationPopWindow.showDownPopwindow(binding.carFunction, true);
                funcationPopWindow.backgroundAlpha(0.5f);
                funcationPopWindow.setData(mlist);
                break;
            case R.id.tv_isunload:
                showPeoplePop();
                break;
            case R.id.rl_choose_time:
                TimePickerView timePicker = new TimePickerBuilder(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String format = sdf.format(date);
                        binding.tvTime.setText(format);
                        acquireTime = date.getTime();
                        viewModel.carInfoEntity.get().setAcquireTime(acquireTime);
                    }
                })
                        .setCancelText("取消").setSubCalSize(15)
                        .setCancelColor(Color.parseColor("#666666"))
                        .setTitleText("选择日期")
                        .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                        .setSubmitText("确定")
                        .setRangDate(null, Calendar.getInstance())
                        .setSubmitColor(Color.parseColor("#5792FD")).build();
                timePicker.show();
                break;
            case R.id.img_del1:
                viewModel.carInfoEntity.get().setMainCertificate("");
                binding.imgDel1.setVisibility(View.GONE);
                binding.ivCertificates.setImageResource(R.drawable.img_cy_zhengmian);
                break;
            case R.id.img_del2:
                viewModel.carInfoEntity.get().setViceCertificate("");
                binding.imgDel2.setVisibility(View.GONE);
                binding.ivCertificatesCarphoto.setImageResource(R.drawable.img_cy_fuye);
                break;
            case R.id.img_del3:
                viewModel.carInfoEntity.get().setTransportCertificateMain("");
                binding.imgDel3.setVisibility(View.GONE);
                binding.ivTransportCertificates.setImageResource(R.drawable.img_daoluzhuye);
                break;
            case R.id.car_upper_door_address:
                //AMapDialog.launch(this);
                showCityPop();
                break;
            case R.id.car_insurance_time:
                setInsuranceTime();
                break;
            case R.id.car_annual_inspection_time:
                setInspectionTime();
                break;
            case R.id.car_maintenance_time:
                TimePickerView maintenancetime = new TimePickerBuilder(this, new OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date, View v) {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String format = sdf.format(date);
                        binding.carMaintenanceTime.setText(format);
                        upMaintainTime = date.getTime();
                        viewModel.carInfoEntity.get().setUpMaintainTime(upMaintainTime);
                    }
                })
                        .setCancelText("取消").setSubCalSize(15)
                        .setCancelColor(Color.parseColor("#666666"))
                        .setTitleText("选择日期")
                        .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                        .setSubmitText("确定")
                        .setRangDate(null, Calendar.getInstance())
                        .setSubmitColor(Color.parseColor("#5792FD")).build();
                maintenancetime.show();
                break;
            case R.id.car_current_go:
                showCityPopGo();
                break;
            case R.id.ll_vehicle_energy_type:
                if (entityList==null) {
                    viewModel.getCarEnergy();
                }
                if (mEnergyPicker!=null) {
                    mEnergyPicker.show();
                }
                break;
        }
    }
    private void setInsuranceTime(){
        TimePickerView timePickerinsurance = new TimePickerBuilder(this, (date, v) -> {
            @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(date);
            binding.carInsuranceTime.setText(format);
            insuranceTime = date.getTime();
            viewModel.carInfoEntity.get().setInsuranceTime(insuranceTime);
        }).setType(new boolean[]{true, true, true, false, false, false}).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .setTitleText("选择日期")
               .build();
        timePickerinsurance.show();
    }
private void setInspectionTime(){
    TimePickerView timePickerinspection = new TimePickerBuilder(this, (date, v) -> {
        @SuppressLint("SimpleDateFormat") SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String format = sdf.format(date);
        binding.carAnnualInspectionTime.setText(format);
        annualInspectionTime = date.getTime();
        viewModel.carInfoEntity.get().setAnnualInspectionTime(annualInspectionTime);
    }).setType(new boolean[]{true, true, true, false, false, false}).setCancelText("取消").setSubCalSize(15)
            .setCancelColor(Color.parseColor("#666666"))
            .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
            .setSubmitText("确定")
            .setSubmitColor(Color.parseColor("#5792FD"))
            .setTextColorCenter(Color.parseColor("#ff333333"))
            .setContentTextSize(15)
            .setLineSpacingMultiplier(2.5f)
            .setTitleText("选择日期")
            .setDividerColor(Color.parseColor("#EDEDED"))
            .build();
    timePickerinspection.show();
}
    private void showPeoplePop() {
        List<String> unloadlist = Arrays.asList("自卸", "非自卸");
        OptionsPickerView businessOption;
        businessOption = PickerHelper.with(this).getCommonPicker("是否自卸", unloadlist, (options1, options2, options3, v) -> {
            String content = unloadlist.get(options1);
            if (content.equals("自卸")) {
                viewModel.carInfoEntity.get().setIsDump(1);
            } else {
                viewModel.carInfoEntity.get().setIsDump(0);
            }
            binding.tvIsunload.setText(content);
        });
        businessOption.show();
    }

    private void showPictureDailog(int pic, int type) {
        mChoosePictureDialog = new ChoosePictureDialog(getActivity(), pic);
        mChoosePictureDialog.setDialogClickCallBack(new ChoosePictureDialog.DialogClickCallBack() {
            @Override
            public void onItemClick(String ids) {
                if (ids.equals("拍照")) {
                    getTackPhoto(type);
                } else if (ids.equals("从手机相册选择")) {
                    getCerImage(type);
                }

            }
        });
        mChoosePictureDialog.show(getSupportFragmentManager(), "1");
    }

    private void getCerImage(int type) {
        this.type = type;
        MLog.d("type == ", "" + type);
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .selectionMode(PictureConfig.SINGLE)
                .loadImageEngine(GlideEngine.createGlideEngine())
                .compress(true)//是否压缩
                .minimumCompressSize(4 * 1024)//小于4M不压缩
                .maxSelectNum(1)//判断还能选多少张图片
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    private void getTackPhoto(int type) {
        this.type = type;
  /*      MLog.d("type == ", "" + type);
        PictureSelector.create(this)
                .openCamera(PictureMimeType.ofImage())
                .compress(true)//是否压缩
                .minimumCompressSize(4 * 1024)
                .forResult(PictureConfig.CHOOSE_REQUEST);*/
        if (type == DRIVING_LICENS) {
            CameraActivity.start(this, 1, "从业资格证主页", PictureConfig.REQUEST_CAMERA);
        } else if (type == DRIVING_LICENS_ATTACHED) {
            CameraActivity.start(this, 1, "从业资格证副页", PictureConfig.REQUEST_CAMERA);
        } else if (type == TRANSPORT_PIC) {
            CameraActivity.start(this, 1, "道路运输证主页", PictureConfig.REQUEST_CAMERA);
        }
    }

    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(this, (options1, options2, options3, v) -> {
            String areaName;
            if (opt3.get(options1).get(options2).get(options3) == null) {
                areaName = "";
            } else {
                areaName = opt3.get(options1).get(options2).get(options3).getName();
                cityPosition3 = options3;
                //区
                viewModel.carInfoEntity.get().setCarDistrictName(areaName);
                viewModel.carInfoEntity.get().setCarDistrictNo(opt3.get(options1).get(options2).get(options3).getNo());
            }

            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName()
                    + areaName;
            binding.carUpperDoorAddress.setText(content);
            viewModel.carInfoEntity.get().setCarProvinceName(addressEntityList.get(options1).getName());
            viewModel.carInfoEntity.get().setCarCityName(opt2.get(options1).get(options2).getName());
            viewModel.carInfoEntity.get().setCarProvinceNo(addressEntityList.get(options1).getNo());
            viewModel.carInfoEntity.get().setCarCityNo(opt2.get(options1).get(options2).getNo());
            cityPosition1 = options1;
            cityPosition2 = options2;


        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleText("请选择位置")
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .build();

        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();

    }

    private void showCarLengthPop() {

        carLengthPop = PickerHelper.with(this).getCommonPicker("选择车长", carsLengthData, carLengthPosition, (options1, options2, options3, v) -> {
            String content = carsLengthData.get(options1).getName();
            String[] len = content.split("米");
            double carLen = Double.valueOf(len[0]);
            binding.tvCarLengh.setText(content);
            carLengthPosition = options1;
            viewModel.carInfoEntity.get().setCarLenNo(carsLengthData.get(options1).getNo());
            viewModel.carInfoEntity.get().setCarLen(carLen);

        });
        if (carLengthPop != null && !carLengthPop.isShowing())
            carLengthPop.show();

    }

    private void showCarModelPop() {
        if (carModePop == null) {
            carModePop = PickerHelper.with(this).getCommonPicker("选择车型", carsTypeData, carModelPosition, (options1, options2, options3, v) -> {
                String content = carsTypeData.get(options1).getName();
                binding.tvCarModel.setText(content);
                carModelPosition = options1;
                viewModel.carInfoEntity.get().setCarTypeNo(carsTypeData.get(options1).getNo());
                carsLengthData = carsTypeData.get(options1).getCarLenList();
                binding.llCarLengh.setVisibility(View.VISIBLE);
                binding.vLine.setVisibility(View.VISIBLE);
                viewModel.carInfoEntity.get().setCarLenNo("");
                binding.tvCarLengh.setText("");
            });
        }
        if (carModePop != null && !carModePop.isShowing()) {
            carModePop.show();
        }
    }

    //车辆颜色
    private void showCarColorPop() {
        OptionsPickerView businessOption = PickerHelper.with(this).getCommonPicker("选择车牌颜色", carColorInfo, carColorPostition, (options1, options2, options3, v) -> {
            String content = carColorInfo.get(options1).getName();
            viewModel.carInfoEntity.get().setLicensePlateColor(carColorInfo.get(options1).getNo());
            binding.tvCarColor.setText(content);
            carColorPostition = cityPosition1;
        });
        businessOption.setSelectOptions(carColorPostition);
        businessOption.show();
    }
    //能源类型
    private void showCarEnergyPop(List<EnergyTypeEntity> list) {
        if (ArrayUtil.isNullOrEmpty(list)) {
            return;
        }
        mEnergyPicker = PickerHelper.with(this).getCommonPicker("选择能源类型", list, ((options1, options2, options3, v) -> {
            EnergyTypeEntity entity = list.get(options1);
            viewModel.carInfoEntity.get().setImageSourceCode(entity.getNo());
            binding.vehicleEnergyType.setText(entity.getName());
        }));
    }

    //获取车型
    public void getCarsTypeData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            carsTypeData = list;
            showCarModelPop();
        } else {
           // MToast.showToast(getActivity(), "数据未加载");
        }
    }

    //获取车长
    public void getCarsLengthData(List<GoodsInfoTypeEntity3> list) {
        if (null != list && list.size() > 0) {
            carsLengthData = list;
        } else {
           // MToast.showToast(getActivity(), "数据未加载");
        }
    }

    public void initAddressData(List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        addressEntityList = datas;
        Log.v("public==source", datas.size() + "");
        initJsonData();
    }

    private void initJsonData() {

        for (int i = 0; i < addressEntityList.size(); i++) {

            ArrayList areaList = new ArrayList<>();
            opt2.add(addressEntityList.get(i).getChildren());
            for (int j = 0; j < addressEntityList.get(i).getChildren().size(); j++) {

                List<AddressEntity> cityAreaList = new ArrayList<>();
                List<AddressEntity> children = addressEntityList.get(i).getChildren().get(j).getChildren();
                if (children == null || children.size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(children);
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    MLog.d("type ", type + "");
                    if (type == DRIVING_LICENS) {

                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        File file = new File(selectList.get(0).getCompressPath());
                        MLog.d("图片路径：", selectList.get(0).getCompressPath());
                        if (file.exists()) {
                            MLog.d("图片", "存在");
                        }

                        Glide.with(getActivity()).load(selectList.get(0).getCompressPath()).apply(new RequestOptions().centerCrop()).into(binding.ivCertificates);
                        vehicleLicenseFile = file;
                        binding.imgDel1.setVisibility(View.VISIBLE);

                        driverPic = "";
                        viewModel.uploadMutiFileModel(this,ImageUtil.getImage(selectList.get(0).getCompressPath()), DRIVING_LICENS);

                    } else if (type == DRIVING_LICENS_ATTACHED) {

                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        File file = new File(selectList.get(0).getCompressPath());
                        MLog.d("图片路径：", selectList.get(0).getCompressPath());
                        if (file.exists()) {
                            MLog.d("图片", "存在");
                        }

                        binding.imgDel2.setVisibility(View.VISIBLE);
                        Glide.with(getActivity()).load(selectList.get(0).getCompressPath()).apply(new RequestOptions().centerCrop()).into(binding.ivCertificatesCarphoto);
                        vehicleLicenseFile2 = file;


                        viewModel.uploadMutiFileModel(this,ImageUtil.getImage(selectList.get(0).getCompressPath()), DRIVING_LICENS_ATTACHED);
                    } else if (type == TRANSPORT_PIC) {
                        List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                        File file = new File(selectList.get(0).getCompressPath());
                        MLog.d("图片路径：", selectList.get(0).getCompressPath());
                        if (file.exists()) {
                            MLog.d("图片", "存在");
                        }

                        binding.imgDel3.setVisibility(View.VISIBLE);
                        Glide.with(getActivity()).load(selectList.get(0).getCompressPath()).apply(new RequestOptions().centerCrop()).into(binding.ivTransportCertificates);
                        vehicleLicenseFile3 = file;
                        viewModel.uploadMutiFileModel(this,ImageUtil.getImage(selectList.get(0).getCompressPath()), TRANSPORT_PIC);

                    }
                    break;
                case PictureConfig.REQUEST_CAMERA:
                    MLog.d("type ", type + "");
                    String path = data.getStringExtra("imagePath");
                    if (type == DRIVING_LICENS) {

                        Glide.with(getActivity()).load(path).apply(new RequestOptions().centerCrop()).into(binding.ivCertificates);
                        binding.imgDel1.setVisibility(View.VISIBLE);

                        driverPic = "";
                        viewModel.uploadMutiFileModel(this,new File(path), DRIVING_LICENS);

                    } else if (type == DRIVING_LICENS_ATTACHED) {
                        binding.imgDel2.setVisibility(View.VISIBLE);
                        Glide.with(getActivity()).load(path).apply(new RequestOptions().centerCrop()).into(binding.ivCertificatesCarphoto);


                        viewModel.uploadMutiFileModel(this,new File(path), DRIVING_LICENS_ATTACHED);
                    } else if (type == TRANSPORT_PIC) {
                        binding.imgDel3.setVisibility(View.VISIBLE);
                        Glide.with(getActivity()).load(path).apply(new RequestOptions().centerCrop()).into(binding.ivTransportCertificates);
                        viewModel.uploadMutiFileModel(this,new File(path), TRANSPORT_PIC);

                    }
                    break;
                case RequestCode.CODE_MAP:
                    AMapAddressEntity entity = AMapDialog.get(data);
                    if (entity == null) return;
                     String address;
                    if ((entity.getSnippet().contains("省")|| entity.getSnippet().contains("市"))) {
                        address = entity.getSnippet();
                    } else {
                        address = entity.getAllProvince() + entity.getAllCity() + entity.getAllDistrict() + entity.getSnippet();
                    }
                        binding.tvLocation.setText(address);
                        binding.etCargoOrdersAddress.setVisibility(View.GONE);
                        binding.line1.setVisibility(View.VISIBLE);
                        binding.etCargoOrdersAddress.setText(entity.getSnippet());
                        viewModel.carInfoEntity.get().setProvinceName(entity.getProvince());
                        viewModel.carInfoEntity.get().setProvinceNo(entity.getProvinceNo());
                        viewModel.carInfoEntity.get().setCityName(entity.getCity());
                        viewModel.carInfoEntity.get().setCityNo(entity.getCityNo());
                        viewModel.carInfoEntity.get().setDistrictName(entity.getDistrict());
                        viewModel.carInfoEntity.get().setDistrictNo(entity.getDistrictNo());
                        viewModel.carInfoEntity.get().setDetailAddress(entity.getSnippet());
                        viewModel.carInfoEntity.get().setLatitude(entity.getLatitude());
                        viewModel.carInfoEntity.get().setLongitude(entity.getLongitude());
                    break;

            }
        }
    }

    public void uploadImgSuccess(String info, int type) {
        if (type == DRIVING_LICENS) {
            viewModel.carInfoEntity.get().setMainCertificate(info);
            driverPic = info;
        } else if (type == DRIVING_LICENS_ATTACHED) {
            viewModel.carInfoEntity.get().setViceCertificate(info);
            driverPic2 = info;
        } else {
            viewModel.carInfoEntity.get().setTransportCertificateMain(info);
        }

    }


    @Override
    protected void onPause() {
        super.onPause();
        /*APIManager.getInstance().changeAPIManager(BuildConfig.LOCAL_TEST_URL);*/
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void getCarInfo(LogisticsEvent event) {
        if (event != null && event.getMessageTag() == EventConstant.EVENT_CARINFO) {
            CarInfoEntity infoEntity = (CarInfoEntity) event.getMessageData();
            if (infoEntity != null) {
                viewModel.carInfoEntity.get().setCarImage(infoEntity.getCarImage());
                if (!TextUtils.isEmpty(infoEntity.getTransportCertificateMain())) {
                    viewModel.carInfoEntity.get().setTransportCertificateMain(infoEntity.getTransportCertificateMain());
                    viewModel.carInfoEntity.get().setTransportCertificateVice(infoEntity.getTransportCertificateVice());
                    viewModel.carInfoEntity.get().setTransportCertificateNum(infoEntity.getTransportCertificateNum());
                }
            }
        } else if (event != null && event.getMessageTag() == EventConstant.EVENT_CARINFO_COMMIT) {
            finish();
        }
    }

    public void setMyCarList(List<AllFunction> list) {
        mlist = new ArrayList<>();
        if (!TextUtils.isEmpty(myCarInfo.getFunctionNo())) {
            String[] strings = myCarInfo.getFunctionNo().split(",");
            for (int i = 0; i < list.size(); i++) {
                for (int j = 0; j < strings.length; j++) {
                    if (list.get(i).getNo().equals(strings[j])) {
                        list.get(i).setIsselect(true);
                    }
                }
            }
        }
        this.mlist = list;
        setMlist(mlist);
    }

    public void setMlist(List<AllFunction> entity) {
        sb = new StringBuilder();
        no = new StringBuilder();
        if (entity == null) {
            return;
        }
        for (int i = 0; i < entity.size(); i++) {
            if (entity.get(i).isIsselect()) {
                String string = entity.get(i).getName();
                String nosub = entity.get(i).getNo();
                no.append(nosub);
                no.append(",");
                sb.append(string);
                sb.append(",");
            }
        }
        if (sb.length() == 0) {
            binding.carFunction.setText("");
        } else {
            binding.carFunction.setText(sb.substring(0, sb.length() - 1));
        }
    }

    public void showCityPopGo() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(this, (options1, options2, options3, v) -> {
            String content = addressEntityList.get(options1).getName()
                    + opt2.get(options1).get(options2).getName();
            binding.carCurrentGo.setText(content);
            viewModel.carInfoEntity.get().setIntentionProvinceName(addressEntityList.get(options1).getName());
            viewModel.carInfoEntity.get().setIntentionCityName(opt2.get(options1).get(options2).getName());
            viewModel.carInfoEntity.get().setIntentionProvinceNo(addressEntityList.get(options1).getNo());
            viewModel.carInfoEntity.get().setIntentionCityNo(opt2.get(options1).get(options2).getNo());
            intentioncityPosition1 = options1;
            intentioncityPosition2 = options2;

        }).setCancelText("取消").setSubCalSize(15)
                .setCancelColor(Color.parseColor("#666666"))
                .setTitleColor(Color.parseColor("#969696")).setTitleSize(15)
                .setSubmitText("确定")
                .setSubmitColor(Color.parseColor("#5792FD"))
                .setTextColorCenter(Color.parseColor("#ff333333"))
                .setContentTextSize(15)
                .setLineSpacingMultiplier(2.5f)
                .setDividerColor(Color.parseColor("#EDEDED"))
                .setTitleText("选择城市")
                .build();
        cityOption.setPicker(addressEntityList, opt2);
        cityOption.setSelectOptions(intentioncityPosition1, intentioncityPosition2);
        cityOption.show();

    }
}

